# -*- coding: utf-8 -*-
__author__ = 'yangq'

from appcommon.appinstance import ymanage_pool
from tornado import gen


@gen.coroutine
def get_menu_tree():
    sql_parent = (
        "select menu_id, menu_name from menu_tree where parent_id = -1 "
        "and is_using = 1 "
        "order by sort_id;"
    )
    menu_parent = yield ymanage_pool.get_all(sql_parent, cursor='dict')

    sql_link = (
        "select menu_id, menu_name, link, parent_id from menu_tree where parent_id <> -1 "
        "and is_using = 1 "
        "and power = 0 "
        "order by sort_id;"
    )
    menu_link = yield ymanage_pool.get_all(sql_link, cursor='dict')
    res = []
    for p in menu_parent:
        tmp = dict(
            menu_name=p['menu_name'],
            link_list=[]
        )
        for l in menu_link:
            if l['parent_id'] == p['menu_id']:
                tmp['link_list'].append(dict(
                    link_name=l['menu_name'],
                    link=l['link']
                ))
        res.append(tmp)
    raise gen.Return(res)


@gen.coroutine
def get_manage_menu(menu_type, parent_id, left):
    if menu_type == '0':
        sql = (
            "select menu_id, menu_name, sort_id, link, power from menu_tree where parent_id = -1 "
            "and is_using = 1 "
            "order by sort_id;"
        )
        tmp = yield ymanage_pool.get_all(sql, cursor='dict')
        if left:
            res = dict(
                code='0',
                info=tmp
            )
        else:
            res = dict(
                total=len(tmp),
                rows=tmp
            )
    else:
        sql = (
            "select menu_id, menu_name, link, power, sort_id from menu_tree where parent_id <> -1 "
            "and is_using = 1 "
            "and parent_id = {} "
            "order by sort_id;"
        )
        tmp = yield ymanage_pool.get_all(sql.format(parent_id), cursor='dict')
        res = dict(
            total=len(tmp),
            rows=tmp
        )
    raise gen.Return(res)


@gen.coroutine
def update_manage_menu(args):
    print args['menu_name']
    if args['menu_id']:
        sql = (
            "update menu_tree set menu_name = '{menu_name}', link = '{link}', power='{power}', sort_id='{sort_id}' where "
            "is_using = 1 and menu_id = '{menu_id}'"
        )
        yield ymanage_pool.update(sql.format(**args))
    else:
        sql = (
            "insert into menu_tree (menu_name, link, parent_id, power, sort_id) "
            "values ('{menu_name}','{link}',{parent_id},{power},{sort_id})"
        )
        yield ymanage_pool.update(sql.format(**args))
    res = 0
    raise gen.Return(res)


@gen.coroutine
def del_manage_menu(menu_id):
    print menu_id
    sql = (
        "delete from menu_tree where menu_id = {} "
    )
    res = yield ymanage_pool.update(sql.format(menu_id))
    raise gen.Return(res)
